package com.kangfu.api.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.kangfu.api.interceptor.AuthorizationInterceptor;
import com.kangfu.api.service.IHuaweiService;
import com.kangfu.common.annotation.IgnoreAuth;
import com.kangfu.common.constant.SystemConstant;
import com.kangfu.common.model.AjaxResult;
import com.kangfu.common.utils.RedisUtils;
import com.kangfu.db.domain.entity.User;
import com.kangfu.db.mapper.UserMapper;
import com.kangfu.db.model.request.ReceviceDataRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Controller
@RequestMapping("/huawei")
public class HuaweiController {
    private static final Logger logger = LoggerFactory.getLogger(HuaweiController.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IHuaweiService huaweiService;

    @Autowired
    private UserMapper userMapper;

    public static final String successUri = SystemConstant.API_URL + "/questionaire/success.html";

    public static final String errorUri = SystemConstant.API_URL + "/questionaire/error.html";

    /**
     * 去到华为H5授权页面
     * @param response
     * @throws IOException
     */
    @GetMapping("/authorize")
    public void getAuthorizeUrl(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestAttribute(AuthorizationInterceptor.LOGIN_TOKEN_KEY) String token, HttpServletResponse response) throws IOException {
        String huaweiAuthUrl = huaweiService.buildAuthorizeUrl(userId, token);
        logger.info("用户绑定手环 准备跳转h5页面  用户id: " +String.valueOf(userId) + " url：" +huaweiAuthUrl);
        response.sendRedirect(huaweiAuthUrl);
    }

    /**
     * 从华为H5授权页面跳转回来，获取accessToken，并重定向到第四步调查问卷
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/getAccessToken")
    @IgnoreAuth
    public void getAccessToken(@RequestParam(name = "code", defaultValue = "") String code, @RequestParam(name = "state", defaultValue = "") String state, HttpServletResponse response) throws IOException {
        logger.info("用户绑定手环 从华为页面跳转回来  code: " + code + "  ||  state：" + state);
        if (StrUtil.isBlank(code) || StrUtil.isBlank(state)) {
            //去绑定失败的页面
            logger.info("用户绑定手环 从华为页面跳转回来 绑定失败1");
            response.sendRedirect(errorUri);
        }
        Integer userId = (Integer) redisUtils.get(state);
        if (userId == 0) {
            //去绑定失败的页面
            logger.info("用户绑定手环 从华为页面跳转回来 绑定失败2");
            response.sendRedirect(errorUri);
        }
        String token = (String) redisUtils.get(state + "_token");
        //根据code获取accessToken
        huaweiService.getAccessTokenByCode(code, userId);
        response.sendRedirect(successUri);
        //todo 先过华为的检查
//        //检查用户基本资料的登记
//        UserInfo userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 4,1);
//        if (userInfo == null) {
//            String url = SystemConstant.API_URL + "/questionaire/userinfo-4.html?subType=1&X-KANNGFU-TOKEN=" + token;
//            response.sendRedirect(url);
//        } else {
//            //如果用户已经填写了第四步调查问卷，就直接去绑定成功页面
//            response.sendRedirect(successUri);
//        }
    }


    @GetMapping("/success")
    @IgnoreAuth
    public String success() {
        return "success";
    }

    @GetMapping("/error")
    @IgnoreAuth
    public String error() {
        return "error";
    }



    /**
     * 取消华为授权
     * @param userId
     * @return
     */
    @PostMapping("/unauthorize")
    @ResponseBody
    public AjaxResult unAuthorize(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {
        boolean unauthorizeRes = huaweiService.unAuthorize(userId);
        if (unauthorizeRes) {
            return AjaxResult.success("取消授权成功");
        }
        return AjaxResult.error("取消授权失败");
    }


    /**
     *
     * @param type 数据类型   1：步数，2：心率，3：血氧
     * @param dateType  时间类型  1：日，2：周，3：月
     * @param date  时间   格式：yyyy-MM-dd   例如：2022-09-07
     * @param forceRefresh      是否强制从华为拉取数据   1：是，    0：否
     * @return
     */
    @GetMapping("/getDataByType")
    @ResponseBody
    public AjaxResult getDataByType(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId,@RequestParam(name = "type", defaultValue = "1") int type, @RequestParam(name = "dateType", defaultValue = "1") int dateType, @RequestParam(name = "date", defaultValue = "") String date, @RequestParam(name = "forceRefresh", defaultValue = "0") int forceRefresh) {
        User user = userMapper.selectUserById(userId);
        if (dateType == 1) {
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(date, "yyyy-MM-dd");
            if (user.getVersion() == 1) {
                HashMap<String, Object> hashMap = huaweiService.getMinutelyHealthDataList(userId, type, localDateTime, forceRefresh);
                return AjaxResult.success(hashMap);
            } else {
                HashMap<String, Object> hashMap = huaweiService.getMinutelyHealthDataListFromBluetooth(userId, type, localDateTime, forceRefresh);
                return AjaxResult.success(hashMap);
            }
        } else if (dateType == 2) {
            LocalDate localDate = LocalDateTimeUtil.parse(date, "yyyy-MM-dd").toLocalDate();
            LocalDate weekBegin = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate weekEnd = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
            if (user.getVersion() == 1) {
                HashMap<String, Object> hashMap = huaweiService.getDailyHealthDataList(userId, type, weekBegin, weekEnd, forceRefresh);
                return AjaxResult.success(hashMap);
            } else {
                HashMap<String, Object> hashMap = huaweiService.getDailyHealthDataListFromBluetooth(userId, type, weekBegin, weekEnd, forceRefresh);
                return AjaxResult.success(hashMap);
            }
        } else if (dateType == 3) {
            LocalDate localDate = LocalDateTimeUtil.parse(date, "yyyy-MM-dd").toLocalDate();
            LocalDate monthBegin = localDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate monthEnd = localDate.with(TemporalAdjusters.lastDayOfMonth());
            if (user.getVersion() == 1) {
                HashMap<String, Object> hashMap = huaweiService.getDailyHealthDataList(userId, type, monthBegin, monthEnd, forceRefresh);
                return AjaxResult.success(hashMap);
            } else {
                HashMap<String, Object> hashMap = huaweiService.getDailyHealthDataListFromBluetooth(userId, type, monthBegin, monthEnd, forceRefresh);
                return AjaxResult.success(hashMap);
            }
        }
        return AjaxResult.error("参数错误");
    }


    @PostMapping("/receiveData")
    @ResponseBody
    public AjaxResult receiveData(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestBody List<ReceviceDataRequest> list) {
        huaweiService.receiveData(userId, list);
        return AjaxResult.success();
    }
}
